package com.zhipu.balance.ui.vm.home.calculate.corn

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zhipu.balance.common.Constants
import com.zhipu.balance.listener.ChooseClickCallback
import com.zhipu.balance.listener.SerialPortListener
import com.zhipu.balance.mobile.dao.NumberDao
import com.zhipu.balance.mobile.dao.RecordCornDao
import com.zhipu.balance.mobile.event.RecordCorn
import com.zhipu.balance.mobile.event.RecordRice
import com.zhipu.balance.pop.ConfirmPopup
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.calculate.corn.*
import com.zhipu.balance.ui.home.calculate.corn.adapter.CornAdapter
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.OpenSerialPort
import com.zhipu.balance.utils.data.DisposeUtils
import com.zhipu.balance.utils.print.corn.CornPrintUtils
import com.zhipu.balance.utils.upload.corn.CornUploadUtils
import `in`.xiandan.countdowntimer.CountDownTimerSupport
import `in`.xiandan.countdowntimer.OnCountDownTimerListener
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 功能计算-玉米
 */
class CornViewModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService), SerialPortListener, ChooseClickCallback {


    /**
     * 称重重量
     */
    var weighing = ObservableField("0.00")

    /**
     * 去皮
     */
    var peel = ObservableField(false)

    /**
     * 位置
     */
    var mPosition = MutableLiveData(0)

    /**
     * 编号
     */
    var mNumber = ObservableField("")

    /**
     * 日期
     */
    var mInspectionDate = ObservableField("")

    /**
     * 记录玉米
     */
    var mRecordCorn = RecordCorn()



    /**
     * 适配器
     */
    var mCornAdapter : CornAdapter? = null

    /**
     * 是否显示
     */
    var subdivide = ObservableField(false)

    /**
     *  不完善细分
     */
    var mImperfectSubdivision : MutableLiveData<Boolean> = MutableLiveData(SPUtils.getInstance().getBoolean("ImperfectSubdivision",false))

    /**
     *  Fragment集合
     */
    var mFragments = MutableLiveData<List<Fragment>>()

    /**
     * 玉米杂质
     */
    var mCornImpurityFragment = CornImpurityFragment(mRecordCorn)
    /**
     * 玉米不完善粒
     */
    var mCornFaultinessFragment = CornFaultinessFragment(mRecordCorn)

    /**
     * 容重
     */
    var mCornRongZhongFragmnet = CornRongZhongFragmnet(mRecordCorn)

    /**
     * 切换
     */
    var switchover = ObservableField(false)
    /**
     * 倒计时
     */
    var twoCountDownTimerSupport = CountDownTimerSupport(100, 100);
    /**
     * 倒计时
     */
    var threeCountDownTimerSupport = CountDownTimerSupport(100, 100);


    init {
        OpenSerialPort.onSerialPortListener(this)
        /**
         * 每隔milliseconds毫秒后执行next操作
         */
        Observable.interval(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<Long> {

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: Long) {
                /**
                 * 重量輸出命令
                 */
                OpenSerialPort.output()
            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }

        })

        /**
         * 倒计时
         */
        twoCountDownTimerSupport.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            /**
             * 间隔的回调
             *
             * @param millisUntilFinished 剩余的时间
            ) */
            override fun onTick(millisUntilFinished: Long) {

            }

            /**
             * 倒计时完成后的回调
             *
            ) */
            override fun onFinish() {
                if(switchover.get() == true){
                    OpenSerialPort.SwitchTo2000()
                    /**
                     * 倒计时
                     */
                    twoCountDownTimerSupport.reset()
                    twoCountDownTimerSupport.start()
                }

            }

            /**
             * 手动停止计时器的回调
             */
            override fun onCancel() {

            }

        })
        /**
         * 倒计时
         */
        threeCountDownTimerSupport.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            /**
             * 间隔的回调
             *
             * @param millisUntilFinished 剩余的时间
            ) */
            override fun onTick(millisUntilFinished: Long) {

            }

            /**
             * 倒计时完成后的回调
             *
            ) */
            override fun onFinish() {
                if(switchover.get() == true){
                    OpenSerialPort.SwitchTo3000()
                    /**
                     * 倒计时
                     */
                    threeCountDownTimerSupport.reset()
                    threeCountDownTimerSupport.start()
                }

            }

            /**
             * 手动停止计时器的回调
             */
            override fun onCancel() {

            }

        })


        /**
         * Fragment适配器
         */
        var mFragmentList = mutableListOf<Fragment>()
        //玉米杂质
        mFragmentList.add(mCornImpurityFragment)
        //玉米不完善粒
        mFragmentList.add(mCornFaultinessFragment)
        //容重
        mFragmentList.add(mCornRongZhongFragmnet)

        /**
         * Fragment集合
         */
        mFragments.postValue(mFragmentList)
        /**
         * 适配器
         */
        mCornAdapter = CornAdapter(this);

    }


    /**
     * 切换
     */
    fun switchover(ImperfectSubdivision : Boolean){
        mCornFaultinessFragment.switchover(ImperfectSubdivision)
    }



    /**
     * 重量回调
     */
    override fun itemClicked(event: ByteArray?) {
        /**
         * 数值
         */
        val numericalValue = ConvertUtils.bytes2HexString(event)
        if (event!!.size >= 10) {
            if (numericalValue == Constants.FARMAR_500) {
                weighing.set("砝码500")
            } else if (numericalValue == Constants.FARMAR_1000) {
                weighing.set("砝码1000")
            } else if (numericalValue == Constants.FARMAR_2000) {
                weighing.set("砝码2000")
            }else if (numericalValue == Constants.FARMAR_3000) {
                weighing.set("砝码3000")
            } else if (ConvertUtils.bytes2HexString(event) == Constants.CALIBRATION_500) {
                weighing.set("完成定标")
            } else if (ConvertUtils.bytes2HexString(event) == Constants.OVERLOAD) {
                weighing.set("超重")
            } else if (ConvertUtils.bytes2HexString(event) == Constants.SEND_GO_START) {
                InitializeUtils.getDefaultMaker()?.show("去皮成功")
                peel.set(false)
            } else if (numericalValue == Constants.SWITCHOVER_SUCCESSFUL) {
                switchover.set(false)
            } else if (ConvertUtils.bytes2HexString(event) == Constants.SHIELD) {
                weighing.set("校准中")
            } else {
                if(peel.get() == true){
                    /**
                     * 置零命令
                     */
                    OpenSerialPort.ZeroOrder()
                }
                var weight = DisposeUtils.balanceCorrection(event)
                //玉米杂质
                mCornImpurityFragment.setWeighing(weight)
                //玉米不完善粒
                mCornFaultinessFragment.setWeighing(weight)
                //容重
                mCornRongZhongFragmnet.setWeighing(weight)
                weighing.set(weight)
            }
        }
    }

    /**
     * Fragment回调
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun onChooseClickCallback(mInt: Int) {
        mCornAdapter?.notifyDataSetChanged()
        mPosition.postValue(mInt)
        when(mInt){
            0 ->{
                subdivide.set(false)
                //玉米杂质
                mCornImpurityFragment.updateRecordRice(mRecordCorn)
                /**
                 * 倒计时
                 */
                threeCountDownTimerSupport.reset()
                threeCountDownTimerSupport.stop()
                /**
                 * 启动
                 */
                switchover.set(true)
                /**
                 * 切换到2000
                 */
                OpenSerialPort.SwitchTo2000()
                /**
                 * 倒计时
                 */
                twoCountDownTimerSupport.reset()
                twoCountDownTimerSupport.start()
            }
            1 ->{
                subdivide.set(true)
                //玉米不完善粒
                mCornFaultinessFragment.updateRecordRice(mRecordCorn)
                mCornFaultinessFragment.refreshData()
                /**
                 * 倒计时
                 */
                threeCountDownTimerSupport.reset()
                threeCountDownTimerSupport.stop()
                /**
                 * 启动
                 */
                switchover.set(true)
                /**
                 * 切换到2000
                 */
                OpenSerialPort.SwitchTo2000()
                /**
                 * 倒计时
                 */
                twoCountDownTimerSupport.reset()
                twoCountDownTimerSupport.start()
            }
            2 ->{
                subdivide.set(false)
                //容重
                mCornRongZhongFragmnet.updateRecordRice(mRecordCorn)
                /**
                 * 倒计时
                 */
                twoCountDownTimerSupport.reset()
                twoCountDownTimerSupport.stop()
                /**
                 * 启动
                 */
                switchover.set(true)
                /**
                 * 切换到3000
                 */
                OpenSerialPort.SwitchTo3000()
                /**
                 * 倒计时
                 */
                threeCountDownTimerSupport.reset()
                threeCountDownTimerSupport.start()
            }
        }
    }


    /**
     * 更新数据
     */
    fun UpdatePage(productCategoryText : String){
        var mRecordCorn = RecordCornDao.getInstance().QueryByNumber(productCategoryText)
        if(mRecordCorn.recordCornId > 0){
            this.mRecordCorn = mRecordCorn
            //日期
            mInspectionDate.set(TimeUtils.millis2String(mRecordCorn.inspectionDate))
            //玉米杂质
            mCornImpurityFragment.updateRecordRice(mRecordCorn)
            //玉米不完善粒
            mCornFaultinessFragment.updateRecordRice(mRecordCorn)
            //容重
            mCornRongZhongFragmnet.updateRecordRice(mRecordCorn)
        }else{
            //唯一识别码
            mRecordCorn.uniqueId = productCategoryText
            //日期
            mInspectionDate.set(TimeUtils.millis2String(TimeUtils.getNowMills()))
        }
        //编号
        mNumber.set(productCategoryText)

    }

    /**
     * 释放更新页面
     */
    fun releaseRecordRice(){
        mRecordCorn = RecordCorn()
        //玉米杂质
        mCornImpurityFragment.releaseRecordRice()
        //玉米不完善粒
        mCornFaultinessFragment.releaseRecordRice()
        //容重
        mCornRongZhongFragmnet.releaseRecordRice()
        //编号
        mNumber.set("")
        //日期
        mInspectionDate.set("")
    }


    /**
     * 更新页面
     */
    fun updatePage(mRecordCorn : RecordCorn){
        this.mRecordCorn = mRecordCorn
        //编号
        mNumber.set(mRecordCorn.uniqueId)
        //日期
        mInspectionDate.set(TimeUtils.millis2String(mRecordCorn.inspectionDate))
        //玉米杂质
        mCornImpurityFragment.updateRecordRice(mRecordCorn)
        //玉米不完善粒
        mCornFaultinessFragment.updateRecordRice(mRecordCorn)
        //容重
        mCornRongZhongFragmnet.updateRecordRice(mRecordCorn)

    }


    /**
     * 保存
     */
    fun save(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    //唯一识别码
                    mRecordCorn.uniqueId = mNumber.get()
                    //判断
                    if(mRecordCorn.recordCornId > 0){
                        //设备码
                        mRecordCorn.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        mRecordCorn.update()
                    }else{
                        //设备码
                        mRecordCorn.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        if(mRecordCorn.save()){
                            /**
                             * 上传
                             */
                            val NetworkSettings = SPUtils.getInstance().getString("NetworkSettings")
                            if(TextUtils.isEmpty(NetworkSettings)){
                                //外网上传玉米天平数据
                                CornUploadUtils.uploadCornBalanceInfo(mRecordCorn,null)
                            }else{
                                //内网上传玉米天平数据
                                CornUploadUtils.IntranetCornBalanceInfo(mRecordCorn,null)
                            }
                        }
                    }
                    /**
                     * 释放更新页面
                     */
                    releaseRecordRice()
                    /**
                     * 数量加一
                     */
                    SPUtils.getInstance().put("number", SPUtils.getInstance().getInt("number") + 1)
                }
            }
        },"确认要进行上传并保存吗\n确认之后会进行新一轮的计算")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }


    /**
     * 打印
     */
    fun print(){
        if(InitializeUtils.isLinkPrinter()){
            var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
                override fun onChooseClickCallback(mInt: Int) {
                    if(mInt == 0){
                        CornPrintUtils.CornPrinting(mRecordCorn)
                    }
                }
            },"确认需要打印吗?")
            XPopup.Builder(ActivityUtils.getTopActivity())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .autoOpenSoftInput(false)
                .asCustom(mConfirmPopup)
                .show()
        }else{
            InitializeUtils.getDefaultMaker()?.show("正在链接打印机")
            InitializeUtils.LinkPrinterModel(ActivityUtils.getTopActivity())
        }
    }

    /**
     * 去皮
     */
    fun peel(){
        InitializeUtils.getDefaultMaker()?.show("正在去皮请稍后")
        /**
         * 去皮
         */
        peel.set(true)
        /**
         * 置零命令
         */
        OpenSerialPort.ZeroOrder()
    }

    /**
     * 计算
     */
    fun calculation(){
        when(mPosition.value){
            0->{
                //玉米杂质
                mCornImpurityFragment.calculation()
            }
            1->{
                //玉米不完善粒
                mCornFaultinessFragment.calculation()
            }
            2->{
                //容重
                mCornRongZhongFragmnet.calculation()
            }
        }
        /**
         *  编号
         */
        if(TextUtils.isEmpty(mNumber.get())){
            var number = NumberDao.getInstance().acquireNumber()
            if(null != number){
                if(SPUtils.getInstance().getLong("NumberedDate") > 0){
                    val DAY = TimeUtils.getTimeSpan(
                        SPUtils.getInstance().getLong("NumberedDate"),
                        TimeUtils.getNowMills(),
                        TimeConstants.DAY
                    )
                    if (DAY == 0L) {
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordCorn.uniqueId = numberString
                        mNumber.set(numberString)
                    }else{
                        SPUtils.getInstance().put("number", 1)
                        SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordCorn.uniqueId = numberString
                        mNumber.set(numberString)
                    }
                }
            }
        }
        /**
         * 日期
         */
        var getNowMills = TimeUtils.getNowMills()
        mInspectionDate.set(TimeUtils.millis2String(getNowMills))
        mRecordCorn.inspectionDate = getNowMills
    }
    /**
     * 主菜单
     */
    fun mainMenu(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    ActivityUtils.finishActivity(CornActivity::class.java)
                }
            }
        },"返回主菜单会导致当前数据丢失")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }
}